package william.list;

/**
 * @author ZhangShenao
 * @date 2024/1/14
 * @description <a href="https://leetcode.cn/problems/middle-of-the-linked-list/description/">...</a>
 */
public class Leetcode876_链表的中间结点 {
    private class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 采用快、慢双指针法,快指针每次前进2个节点,慢指针每次前进1个节点,
     * 当快指针移动到链表末尾时,慢指针刚好指向链表的中间节点
     */
    public ListNode middleNode(ListNode head) {
        //边界条件校验
        if (head == null) {
            return null;
        }

        //采用快、慢双指针法,快指针每次前进2个节点,慢指针每次前进1个节点
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }

        //当快指针移动到链表末尾时,慢指针刚好指向链表的中间节点
        return slow;
    }
}
